# this should be run on intensities dat.out presorted on Q (column 8 or 9)
BEGIN{
  STDE="/dev/stderr";
  qpamin=1000;qpemin=1000;fmin=1000;
  print "# N  HKL  NLAB_1 NLAB_2  |F_1| |F_2|  Qpar_1 Qper_1 Qpar_2 Qper_2";
}
FNR>2{
#  print FNR-2,$3,$4,$5;
  if(!e[$3,$4,$5]){
    e[$3,$4,$5]=FNR-2;
    q[$3,$4,$5]=$11" "$12;
    f[$3,$4,$5]=$1;
  }else if(!q2q[e[$3,$4,$5]" "$1]){
    q2q[e[$3,$4,$5]" "$1]=1;
    nmu++;
    split(q[$3,$4,$5],a);
    if(a[1]<qpamin){qpamin=a[1]};
    if(a[2]<qpemin){qpemin=a[2]};
    if(a[1]>qpamax){qpamax=a[1]};
    if(a[2]>qpemax){qpemax=a[2]};
    if(f[$3,$4,$5]<fmin){fmin=f[$3,$4,$5]};
    if(f[$3,$4,$5]>fmax){fmax=f[$3,$4,$5]};
#    print nmu,$3,$4,$5" (q="$11" "$12")  "FNR-2,"vs",e[$3,$4,$5]" (q="q[$3,$4,$5]")";
    print nmu,$3,$4,$5," ",FNR-2,e[$3,$4,$5]," ",$1,f[$3,$4,$5]," ",$11" "$12,q[$3,$4,$5];
  };
  if($14){
    for(i=1;i<=$14;i++){
      c1=14+(i-1)*3+1;
      c2=14+(i-1)*3+2;
      c3=14+(i-1)*3+3;
      if(!e[$c1,$c2,$c3]){
	e[$c1,$c2,$c3]=FNR-2;
	q[$c1,$c2,$c3]=$11" "$12;
	f[$c1,$c2,$c3]=$1;
      }else if (!q2q[e[$c1,$c2,$c3]" "$1]){
	q2q[e[$c1,$c2,$c3]" "$1]=1;
	split(q[$c1,$c2,$c3],a);
	if(a[1]<qpamin){qpamin=a[1]};
	if(a[2]<qpemin){qpemin=a[2]};
	if(a[1]>qpamax){qpamax=a[1]};
	if(a[2]>qpemax){qpemax=a[2]};
	if(f[$c1,$c2,$c3]<fmin){fmin=f[$c1,$c2,$c3]};
	if(f[$c1,$c2,$c3]>fmax){fmax=f[$c1,$c2,$c3]};
	nmu++;
#	print nmu,$c1,$c2,$c3" (q="$11" "$12") "FNR-2,"vs",e[$c1,$c2,$c3]" (q="q[$c1,$c2,$c3]")";
	print nmu,$c1,$c2,$c3," ",FNR-2,e[$c1,$c2,$c3]," ",$1,f[$c1,$c2,$c3]," ",$11" "$12,q[$c1,$c2,$c3];
      };  
    };
  };
};
END{
  if(nmu){
    print "Mapping deca2hkl: "nmu" datapoints were multiply defined." > STDE;
#    print fmin"<|F|<"fmax > STDE;
#    print qpamin"<Qpara<"qpamax > STDE; 
#    print qpemin"<Qperp<"qpemax > STDE;
  }else{
#    print "Mapping deca2app data: all datapoints were mapped uniquely"> STDE;
  }
}
